/*
 *    Copyright (c) 2018-2025, bpm All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: bpm
 */
import request from '@/utils/request';
import qs from 'qs';
import useUserStore from '@/store/modules/userinfo';
import { Session, Local } from '@/utils/storage';
import website from '@/utils/website';

const scope = 'server';

export const loginByUsername = (username: any, password: any, code: any, randomStr: any) => {
	const grant_type = 'password';
	const dataObj = qs.stringify({ username: username, password: password });
	const basicAuth = 'Basic ' + window.btoa(website.formLoginClient);

	// 保存当前选中的 basic 认证信息
	// setStore({
	// 	name: 'basicAuth',
	// 	content: basicAuth,
	// 	type: 'Session',
	// });
	Session.set('basicAuth', basicAuth);

	return request({
		url: '/auth/oauth/token',
		headers: {
			isToken: false,
			'TENANT-ID': '1',
			Authorization: basicAuth,
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
		},
		method: 'post',
		params: { randomStr, code, grant_type },
		data: dataObj,
	});
};

export const refreshToken = () => {
	const grant_type = 'refresh_token';
	// 获取当前选中的 basic 认证信息
	const basicAuth = Session.get('basicAuth');
	const refresh_token = Local.get('refresh_token');
	console.log('refreshToken--', basicAuth);
	return request({
		url: '/auth/oauth/token',
		headers: {
			isToken: false,
			'TENANT-ID': '1',
			Authorization: basicAuth,
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
		},
		method: 'post',
		params: { refresh_token, grant_type, scope },
	});
};

export const getUserInfo = () => {
	return request({
		url: '/admin/user/info',
		method: 'get',
	});
};

export const logout = () => {
	return request({
		url: '/auth/token/logout',
		method: 'delete',
	});
};

/**
 * 校验令牌，若有效期小于半小时自动续期
 * @param refreshLock
 */
export const checkToken = (refreshTime: any, refreshLock: boolean) => {
	const token = useUserStore().access_token;
	// 获取当前选中的 basic 认证信息
	const basicAuth = Session.get('basicAuth');

	request({
		url: '/auth/oauth/check_token',
		headers: {
			isToken: false,
			Authorization: basicAuth,
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
		},
		method: 'get',
		params: { token },
	})
		.then((response) => {
			const expire = response && response.data && response.data.exp;
			if (expire) {
				const expiredPeriod = expire * 1000 - new Date().getTime();
				//小于半小时自动续约
				if (expiredPeriod <= 30 * 60 * 1000) {
					if (!refreshLock) {
						refreshLock = true;
						useUserStore()
							.refreshToken()
							.catch(() => {
								clearInterval(refreshTime);
							});

						refreshLock = false;
					}
				}
			}
		})
		.catch((error) => {
			console.error(error);
		});
};

/**
 * 注册用户
 */
export const registerUser = (userInfo: object) => {
	return request({
		url: '/admin/register/user',
		method: 'post',
		data: userInfo,
	});
};
